﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Microsoft.Live;
using InventoryManagementSystem.DataModel;
using Windows.UI.Popups;
using Infrastructure.UI;
using Windows.System;

namespace InventoryManagementSystem
{
    public sealed partial class MainPage : InventoryManagementSystem.Common.LayoutAwarePage
    {
        public MainPage()
        {
            this.InitializeComponent();

            this.EnablePrivacyPolicy(PrivacyPolicy.RunXiaDianQi);
        }

        protected override async void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            await DataStore.Initialize();

            //ShowInProgress("正在登录");

            //if (await DataStore.Initialize())
            //{
            //login:
            //    var liveAuthClient = new LiveAuthClient("http://inventorymanagement.lifehelper.net");
            //    await liveAuthClient.InitializeAsync();
            //    if (liveAuthClient.Session == null)
            //    {
            //        var liveLoginResult = await liveAuthClient.LoginAsync(new string[] { "wl.basic wl.signin wl.offline_access wl.emails" });
            //        if (liveLoginResult.Status != LiveConnectSessionStatus.Connected)
            //        {
            //            var loginErrorMessageDialog = new MessageDialog("登录失败，请重试");
            //            await loginErrorMessageDialog.ShowAsync();
            //            goto login;
            //        }
            //    }

            //    var liveConnectClient = new LiveConnectClient(liveAuthClient.Session);
            //    var liveMe = await liveConnectClient.GetAsync("me");
                
            //    var liveMePicture = await liveConnectClient.GetAsync("me/picture");

            //    var user = new User();
            //    user.Email = (string)((IDictionary<string, object>)liveMe.Result["emails"])["account"];
            //    user.Name = (string)liveMe.Result["name"];
            //    user.Picture = (string)liveMePicture.Result["location"];
            //    user.AuthenticationToken = liveAuthClient.Session.AuthenticationToken;

            //    Session.User = user;
            //    //Session.Permission = await DataStore.LoginAsync(user);
            //}

            //DefaultViewModel["User"] = Session.User;

            //HideInProgress();
        }

        protected override void SaveState(Dictionary<String, Object> pageState)
        {
        }

        private void sellButton_Click(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof(SellPage));
        }

        private void purchaseButton_Click(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof(PurchasePage));
        }

        private async void inventoryButton_Click(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof(InventoryPage));
        }

        private async void reportButton_Click(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof(ReportPage));
        }

        private void settingsButton_Click(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof(SettingsPage));
        }

        private async void inventoryUpdateButton_Click(object sender, RoutedEventArgs e)
        {
            ShowInProgress("正在盘库");

            if (await DataStore.MergeCacheAsync())
            {
                var successDialog = new MessageDialog("盘库完成");
                await successDialog.ShowAsync();
            }
            else
            {
                var errorDialog = new MessageDialog("盘库失败");
                await errorDialog.ShowAsync();
            }

            HideInProgress();
        }

        //private async void uploadButton_Click(object sender, RoutedEventArgs e)
        //{
        //    uploadButton.IsEnabled = false;
        //    contentGrid.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
        //    syncProgressRingStackPanel.Visibility = Windows.UI.Xaml.Visibility.Visible;

        //    if (await DataStore.MergeCacheAsync())
        //    {
        //        var successDialog = new MessageDialog("数据上传成功");
        //        await successDialog.ShowAsync();
        //    }
        //    else
        //    {
        //        var errorDialog = new MessageDialog("数据上传失败");
        //        await errorDialog.ShowAsync();
        //    }

        //    contentGrid.Visibility = Windows.UI.Xaml.Visibility.Visible;
        //    syncProgressRingStackPanel.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
        //    uploadButton.IsEnabled = true;
        //}

        //private async void restoreButton_Click(object sender, RoutedEventArgs e)
        //{
        //    var confirmDialog = new MessageDialog("数据恢复将清除所有本地数据，确定要继续吗？");
        //    confirmDialog.Commands.Add(new UICommand("确定", null, 0));
        //    confirmDialog.Commands.Add(new UICommand("取消", null, 1));
        //    confirmDialog.DefaultCommandIndex = 1;
        //    var confirm = await confirmDialog.ShowAsync();
        //    if ((int)confirm.Id != 0)
        //        return;

        //    uploadButton.IsEnabled = false;
        //    contentGrid.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
        //    syncProgressRingStackPanel.Visibility = Windows.UI.Xaml.Visibility.Visible;

        //    if (await DataStore.DownloadDataAsync())
        //    {
        //        var successDialog = new MessageDialog("数据恢复成功");
        //        await successDialog.ShowAsync();
        //    }
        //    else
        //    {
        //        var errorDialog = new MessageDialog("数据恢复失败");
        //        await errorDialog.ShowAsync();
        //    }

        //    contentGrid.Visibility = Windows.UI.Xaml.Visibility.Visible;
        //    syncProgressRingStackPanel.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
        //    uploadButton.IsEnabled = true;
        //}

        private void ShowInProgress(string text)
        {
            inProgressTextBlock.Text = text;
            toolBarStackPanel.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            contentGrid.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            inProgressRingStackPanel.Visibility = Windows.UI.Xaml.Visibility.Visible;
        }

        private void HideInProgress()
        {
            toolBarStackPanel.Visibility = Windows.UI.Xaml.Visibility.Visible;
            contentGrid.Visibility = Windows.UI.Xaml.Visibility.Visible;
            inProgressRingStackPanel.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
        }

        private async void helpButton_Click(object sender, RoutedEventArgs e)
        {
            await Launcher.LaunchUriAsync(new Uri("http://inventorymanagement.lifehelper.net/Help.aspx"));
        }
    }
}
